package com.my.magicApi.utils;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.support.PageableExecutionUtils;

import java.util.ArrayList;
import java.util.List;

public class CachePageUtils {

    /**
     * list 集合内存分页
     * @param pageNumber
     * @param pageSize
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Page<T> selectPageList(int pageNumber, int pageSize, List<T> data) {
        int offset = (pageNumber - 1) * pageSize;
        int totalRow = data.size();
        int totalPage = totalRow / pageSize;
        boolean flag = true; // 分页是否刚好整除
        if (totalRow % pageSize != 0) {
            totalPage++;
            flag = false;
        }
        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);

        if (pageNumber > totalPage) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageable, () -> totalRow);
        }

        int limit = offset + pageSize;
        if (limit >= totalRow) {
            if (offset < totalRow && !flag) {
                // 取最后一页所有元素
                int index = (totalPage - 1) * pageSize; // 最后一页之前的下标
                return PageableExecutionUtils.getPage(data.subList(index, totalRow), pageable, () -> totalRow);
            }
            return PageableExecutionUtils.getPage(data.subList(offset, totalRow), pageable, () -> totalRow);
        }

        Page<T> page = PageableExecutionUtils.getPage(data.subList(offset, limit), pageable, () -> totalRow);
        return page;
    }

}
